using System;
using System.Text.RegularExpressions;
using System.Windows.Media;

namespace TicTacToe.Core
{
    public sealed class Player
    {
        public string Name { get; private set; }
        public Color Color { get; private set; }

        readonly string _id;
        public string ID
        {
            get { return _id; }
        }

        public static bool operator ==(Player a, Player b)
        {
            return a.Equals(b);
        }

        public static bool operator !=(Player a, Player b)
        {
            return !(a == b);
        }

        public override string ToString()
        {
            return Name;
        }

        public static bool IsValidName(string nameStr)
        {
            return Regex.IsMatch(nameStr, @"^\w{1,40}$");
        }

        public Player(string name, Color color)
            : this(name, color, Guid.NewGuid().ToString())
        {
        }

        public Player(string name, Color color, string id)
        {
            if (!IsValidName(name))
                throw new ArgumentException("Given name is invalid", "name");

            Name = name;
            Color = color;
            _id = id;
        }

        public bool Equals(Player other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Equals(other.ID, ID);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof (Player)) return false;
            return Equals((Player) obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int result = (ID != null ? ID.GetHashCode() : 0);
                result = (result*397) ^ (Name != null ? Name.GetHashCode() : 0);
                result = (result*397) ^ Color.GetHashCode();
                return result;
            }
        }
    }
}